// 判断是否有特殊情况
const data = require('./data/data.json')
const fs = require('fs')
const request = require('request')
const { log } = require('console')
const lodash = require('lodash')

// 分析薪资待遇
function countWage() {
  let reg = /(\d+)/g

  let result_obj = {
    '小于 5K': [],
    '5-10K': [],
    '10-15K': [],
    '15-20K': [],
    '大于 20K': [],
  }
  data.forEach((item) => {
    // 去除实习薪资
    if (item['wage'].indexOf('元') >= 0) {
      return
    }
    //去除公司虚假额度薪资
    let wage = parseInt(item['wage'].match(reg)[1]) - 1

    if (wage < 5) {
      result_obj['小于 5K'].push(item)
    } else if (5 <= wage && wage < 10) {
      result_obj['5-10K'].push(item)
    } else if (10 <= wage && wage < 15) {
      result_obj['10-15K'].push(item)
    } else if (15 <= wage && wage < 20) {
      result_obj['15-20K'].push(item)
    } else {
      result_obj['大于 20K'].push(item)
    }
  })

  let result = []
  let keys = Object.keys(result_obj)
  keys.forEach((item) => {
    result.push({
      name: item,
      value: result_obj[item].length,
    })
  })
  log('分析薪资待遇:')
  log(result)
}

// 统计福利待遇
function countWellBing() {
  let data_list = data.map((value, index) => {
    return value.well_bing.split('，')
  })
  let result = resetListFormate(data_list.flat())
  log('词云: 福利待遇分析 - https://wordart.com/create')
  log('数据体')
  log(result)
}

/**
 *   let result = lodash.groupBy(industry_list)
 *   Object.keys(result).map((item) => {
    final_str += item + ';' + result[item].length + '\n'
  })
  log('词云: 行业分析 - https://wordart.com/create')
  log('数据体')
  log(final_str)
 */

function resetListFormate(arr) {
  let result = lodash.groupBy(arr)
  let final_str = ''
  Object.keys(result).map((item) => {
    final_str += item + ';' + result[item].length + '\n'
  })
  return final_str
}

// 统计技能数据
function countSkill() {
  let skill_list = data.map((item, index) => {
    return item.skill_tags
  })
  skill_list = skill_list.flat()
  let result = resetListFormate(skill_list)
  log('词云: 行业分析 - https://wordart.com/create')
  log('数据体')
  log(result)
}

// 统计行业分类
function countType() {
  let industry_list = data.map((item, index) => {
    return item.industry
  })

  let final_arr = []
  let max = 0
  let result = lodash.groupBy(industry_list)
  Object.keys(result).map((item) => {
    if (result[item].length > max) {
      max = result[item].length
    }
  })
  Object.keys(result).map((item) => {
    //   数组 分别是 score ， count ， value
    let itemLength = result[item].length
    final_arr.push([(itemLength / max) * 100, itemLength, `'${item}'`])
  })
  log('行业统计分类：')
  log(final_arr)
}

// 求总数据
function getListDesc() {
  function avgFunc(array) {
    //将array的长度赋给len
    let len = array.length
    let sum = 0
    //利用for循环遍历数组的内容，利用sum累加求和
    for (let i = 0; i < len; i++) {
      sum += array[i]
    }
    //        返回数组的和与长度求平均值
    return sum / len
  }

  let reg = /(\d+)/g
  let wage_list = []
  // 中位数统计
  let middle = 0
  // 平均值统计
  let avg = 0
  data.forEach((item) => {
    // 去除实习薪资
    if (item['wage'].indexOf('元') >= 0) {
      return
    }
    let min = parseInt(item['wage'].match(reg)[0])
    let max = parseInt(item['wage'].match(reg)[1])
    wage_list.push((min + max) / 2)
  })
  wage_list.sort((a, b) => a - b)
  middle = wage_list[parseInt(wage_list.length / 2)]
  avg = avgFunc(wage_list)
  log('----------------------------')
  console.log('岗位总数量：', wage_list.length)
  console.log('工资中位数：', middle)
  console.log('工资平均值：', avg)
  log('----------------------------')
}

// 获取所有地址
function analysisMapCpunt() {
  //   获取单位所在区域
  // 按照点分配，获得最后一个值
  let list = data.map((item, index) => {
    let temp = item.address.replace(/·/g, '')
    item.address = temp
    return item.address
  })
  // 计算权重
  // 获得数值
  fs.writeFileSync('./data/address.json', JSON.stringify(list))
}

// 地址去重
function getUniqueAddressArray() {
  analysisMapCpunt()
  const addressData = require('./data/address.json')
  let uniSet = new Set(addressData)
  return Array.from(uniSet)
}

// request请求获取坐标地址
/**
 * 数据格式
 * {
 * "南关区净月开发区":{"lng":125.37610053134287,"lat":43.86820140370632}
 * }
 */

// 递归进行数据获取，这样可以保证队列进行
function RequestFunc(arr_list, endRequest, dict = {}) {
  // 如果查询结束，那就结束整个流程
  if (arr_list.length == 0) {
    endRequest(dict)
    return
  }
  // 去除下一个查询地址
  let key = arr_list.pop()
  //   859d16285fd000feec89e9032513f8bb
  request.get(
    {
      url: `https://api.map.baidu.com/geocoder/v2/?address=${encodeURI(
        key
      )}&output=json&ak=5E1e7c5c885c0121ceb04a14bb5f2575`,
    },
    function (err, response, body) {
      if (!err) {
        body = JSON.parse(body)
        dict[key] = body.result.location
      }

      RequestFunc(arr_list, endRequest, dict)
    }
  )
}

function getAllLocations(nextFunction) {
  /**
   * 设计队列
   */
  let arr_list = getUniqueAddressArray()
  //   数据完成了
  let endRequest = (dict) => {
    fs.writeFileSync('./data/address_location.json', JSON.stringify(dict))
    nextFunction && nextFunction()
  }
  // 递归进行数据获取，这样可以保证队列进行
  RequestFunc(arr_list, endRequest)
}

function getAddress(address) {
  return address.replace(/·/g, '')
}
//地址加权算法
/**
 *  职位工资>10k 权重1.2
 *  职位工资<10k 权重1
 *  职位工资>15  权重1.5
 */
function sumRightToAddress(nextFunc) {
  let resetRightFunction = function () {
    const result_data = require('./data/address_location.json')
    let reg = /(\d+)/g

    data.forEach((item, index) => {
      let right = 0
      let wage = parseInt(item['wage'].match(reg)[1]) - 1
      if (wage < 10) {
        right = 1
      } else if (10 <= wage < 15) {
        right = 1.2
      } else {
        right = 1.5
      }

      // 查找所在位置
      let address = getAddress(item.address)
      if (result_data[address].right == undefined) {
        result_data[address].right = 0
      }
      result_data[address].right += right
    })
    fs.writeFileSync(
      './data/address_locationWithRight.json',
      JSON.stringify(result_data)
    )
    nextFunc && nextFunc()
  }
  getAllLocations(resetRightFunction)
}

function resetFormateForAddress() {
  let resetFormate = function () {
    const data = require('./data/address_locationWithRight.json')

    let makeTheNumBig = 8
    let result = {}
    let keys = Object.keys(data)
    keys.forEach((item, index) => {
      result[item] = [data[item]['lng'], data[item]['lat']]
    })
    log('格式化 - 地理位置：')
    console.log(result)

    let reuslt_arr = []
    keys.forEach((item, index) => {
      reuslt_arr.push({
        name: item,
        value: data[item]['right'] * makeTheNumBig,
      })
    })
    log('格式化 - name,value：')
    console.log(reuslt_arr)
  }
  sumRightToAddress(resetFormate)
}

// 求总数据
getListDesc()
// 分析薪资待遇
countWage()
// 统计福利待遇
countWellBing()
// 统计技能数据
countSkill()
// 统计行业分类
countType()
// 地理影响力
resetFormateForAddress()

module.exports = {
  // 分析薪资待遇
  countWage,
  // 统计福利待遇
  countWellBing,
  // 统计技能数据
  countSkill,
  // 统计行业分类
  countType,
  // 求总数据
  getListDesc,
  // 地理影响力
  resetFormateForAddress,
}
